local ROT = require 'rot'

local state = ROT.Class:extend()

local Ability = require 'game.proto.ability'

function state:init(game, play, opt)
    self.game = game
    self.play = play
    self.selected = nil
    self.title = opt and opt.title or 'Perform ability'
    self.type = opt and opt.type or 'ability'
end

local FIRST_KEY = ('a'):byte() - 1
local DIM = { 120, 120, 120 }
local BRIGHT = { 240, 240, 240 }

function state:update()
    local player = self.game.player
    local ability = player.ability
    local display = self.game.display
    display:clear()
    display:write(self.title, 1, 1)

    local j = 0
    for i = 1, #ability do
        local a = Ability[ability[i]]
        if a then
            j = j + 1
            display:write(
                string.char(
                i + FIRST_KEY) .. ') ' .. a.name,
                1, 2 + j,
                self.selected == i and BRIGHT or DIM)
        end
    end

    if self.selected then
        local a = Ability[player.ability[self.selected]]
        display:write(a.name, 40, 1, BRIGHT)
        display:write(a.info, 40, 3, DIM)
        display:write('Range:', 40, 5, BRIGHT)
        display:write('@' .. ('-'):rep(a.range - 1) .. '>', 47, 5, DIM)
    else
        display:write('Nothing selected.', 40, 1, DIM)
    end

    local s = '(a-z selects, [esc] cancels, [enter] confirms)'
    display:write(s, display:getWidth() - #s, display:getHeight())

end

function state:keypressed(key)
    local game = self.game
    local player = game.player
    local ability = player.ability
    if key == '\27' then
        game.state = self.play
    elseif key == '\n' and self.selected then
        local a = Ability[ability[self.selected]]
        game.state = self.play
        a:evoke(player, game)
        game.scene:passTime(10)
    else
        local index = key:byte() - FIRST_KEY
        if ability[index] then
            self.selected = index
        end
    end
end

return state
